﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;

namespace DiscoveryLogic.DataViz.NetworkDiagram.FieldComparers
{
    /// <summary>
    /// 
    /// </summary>
    public class KeyComparer:IAttributeComparer
    {
        #region IAttributeComparer Members

        public AttributeComparerType ComparerType
        {
            get
            {
                return AttributeComparerType.ClassComparer;
            }
        }

        private SqlDbType _FieldDbType;
        ///<summary>
        ///</summary>
        public SqlDbType FieldDbType
        {
            get { return _FieldDbType; }
            set { _FieldDbType = value; }
        }


        ///<summary>
        ///</summary>
        ///<returns></returns>
        public IAttributeComparer Create()
        {
            return new KeyComparer();
        }

        public double Compare(object value1, object value2, double penalty, SqlConnection conn, string unevenDistTableName)
        {
            if (value1 == null || value2 == null)
                return 0.0;
            else if (value1.ToString().ToLower() == value2.ToString().ToLower())
                return 1.00;
            else
                return penalty;
        }


        public object Merge(List<object> values, SqlConnection conn, string unevenDistTableName)
        {
            if (values == null || values.Count == 0)
                return null;

            Dictionary<object, int> countByValues = new Dictionary<object, int>();
            foreach (object obj in values)
            {
                if(obj==null)
                    continue;

                if (!countByValues.ContainsKey(obj))
                    countByValues.Add(obj, 1);
                else
                    countByValues[obj] = countByValues[obj] + 1;
            }

            // check ssn9 first
            if (countByValues.Count > 0)
            {
                object mode = null;
                int count = 0;
                foreach(object obj in countByValues.Keys)
                {
                    if (countByValues[obj] > count)
                    {
                        count = countByValues[obj];
                        mode = obj;
                    }
                }
                return mode;
            }
            else
                return null;
        }

        #endregion
    }
}
